package cn.lxb.emall.gw.filter;

import java.util.Set;

import org.springframework.cloud.gateway.config.conditional.ConditionalOnEnabledFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.MessageBodyDecoder;
import org.springframework.cloud.gateway.filter.factory.rewrite.MessageBodyEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.server.ServerWebExchange;

@Configuration
public class EncryptConfig {
	@Bean
	@ConditionalOnEnabledFilter
	public ConditionalModifyResponseBodyGatewayFilterFactory encodeResponseBodyGatewayFilterFactory(
			ServerCodecConfigurer codecConfigurer, Set<MessageBodyDecoder> bodyDecoders,
			Set<MessageBodyEncoder> bodyEncoders) {
		return new ConditionalModifyResponseBodyGatewayFilterFactory(codecConfigurer.getReaders(), bodyDecoders, bodyEncoders);
	}

	public boolean decodeCondition(ServerWebExchange exchange) {
		if (HttpMethod.GET == exchange.getRequest().getMethod()) {
			return false;
		}
		String contentType = exchange.getRequest().getHeaders().getFirst("Content-Type");
		if (!contentType.matches("(application|text).*")) {
			return false;
		}
		return false;
	}

	public boolean encodeCondition(ServerWebExchange exchange) {
		String contentType = exchange.getResponse().getHeaders().getFirst("Content-Type");
		if (!contentType.matches("(application|text).*")) {
			return false;
		}
		return true;
	}

	public String decodeRequest(ServerWebExchange exchange, String req) {
		return "decoded:" + req;
	}

	public String encodeResponse(ServerWebExchange exchange, String resp) {
		return "encode:" + resp;
	}
}
